<?php session_start();?>
<?php
$response = array(
  'valid' => false,
  'message' => 'Se debe completar el usuario'
);

set_include_path('../140dev/db');
	
require_once('140dev_config.php');	  
require_once('db_lib.php');
	
$oDB = new db;
    
if(!$oDB)
{
	die('Could not connect: ' . mysql_error());
}
	
try{
	if(trim($_SESSION['username']) == trim($_POST['name']))
		$response = array('valid' => true);
	else {
		if( isset($_POST['name']) and strlen($_POST['name']) > 0 ) {
			if(strlen($_POST['name']) > 8) 
				$response = array('valid' => false, 'message' => 'El usuario debe ser de 8 caracteres como máximo');
			else {
				$result = $oDB->select("SELECT * FROM MAST_USERS WHERE LOWER(DS_USER_ID) = TRIM(LOWER('" . $_POST['name'] . "'));");
				if($row = mysqli_fetch_row($result)){
					// User name is registered on another account
    				$response = array('valid' => false, 'message' => 'El usuario ya se encuentra registrado');
				}
				else{
					// User name is available
    				$response = array('valid' => true);
				}
			}
		}
	}
	if(isset($_POST['current_pass']) and strlen($_POST['current_pass']) > 0 ){
		if(strlen($_POST['current_pass']) < 6) 
			$response = array('valid' => false, 'message' => 'La contraseña debe ser de 6 caracteres como mínimo');
		else {
			$result = $oDB->select("SELECT DS_USER_ID, DS_SALT, DS_PWD, ID_USER, DS_USER_NAME, DS_USER_EMAIL FROM MAST_USERS WHERE LOWER(DS_USER_ID) = TRIM(LOWER('" .$_SESSION['username'] . "'));");
			if($row = mysqli_fetch_row($result)){
				$user_name = $row[0];
				$salt = $row[1];			
				$hash = $row[2];
				$hash2 = hash("sha256",  $_POST['current_pass']  . $salt);
				if($hash == $hash2)
					$response = array('valid' => true);
				else
					$response = array('valid' => false, 'message' => 'La contraseña no es correcta');
			}
		}
	}
}
catch(Exception $e){
	print $e;
}	

echo json_encode($response);

?>